package sz.szsmk.citizencard.ui.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chenenyu.router.annotation.Route;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.ShopingActivityBinding;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.response.QuryShopRegionAppRes;
import sz.szsmk.citizencard.model.network.bean.response.QuryShopTypeAppRes;
import sz.szsmk.citizencard.model.network.bean.response.ShopListRes;
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent;
import sz.szsmk.citizencard.mvp.contract.IBusnessContact;
import sz.szsmk.citizencard.mvp.presenter.BusinessPresenter;
import sz.szsmk.citizencard.ui.adapter.BusinessAdapter;
import sz.szsmk.citizencard.ui.adapter.PopRvAdapter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PermissionUtil;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.util.zxyh.CheckContentUtil;
import sz.szsmk.citizencard.widget.MySearchView;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/7/27 13:26
 * description: 消费商家  服务器返回的坐标数据为百度地图数据
 */
@Route("business")
public class BusinessActivity extends IBaseActivity<BusinessPresenter, ShopingActivityBinding> implements
        IBusnessContact.IBusnessView, View.OnClickListener,  IBaseActivity.RequestPermissionCallBack{

    TextView shoplistDistanceTv;

    ImageView arrawType;
    ImageView arrawSer;
    ImageView arrawDis;
    LinearLayout typeLayout;


    private ArrayList<ImageView> arraws;
    private int lastSelected = -1;
    private boolean isPopupWindowShow;

    private BusinessAdapter businessAdapter;

    private ArrayList<String> mDistanceList = new ArrayList<>();
    private ArrayList<String> mServiceList = new ArrayList<>();
    private ArrayList<String> mAreaList = new ArrayList<>();
    private String distanceType = "0";
    private String serviceType = "0";
    private String areaType = "0";
    private String door = "1";
    private int currentPager = 1;
    private LinearLayout layout;

    private PopupWindow popupWindow;
    private RecyclerView popRv;
    private int type = 0;
    private PopRvAdapter popRvAdapter;

    private List<ShopListRes.ShopListInfosBean> shopListInfos = new ArrayList<>();
    private List<QuryShopRegionAppRes.ShopRegionInfosBean> shopRegionInfos;
    private List<QuryShopTypeAppRes.ShopTypeInfosBean> shopTypeInfos;


    //传入的参数  用于 全部商家 标签 直接选中 值是type_id 要与后台id对于
    int shopType = -1;

    @Override
    protected int attachLayoutRes() {
        return R.layout.shoping_activity;
    }

    @Override
    protected void initInjector() {

        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {

        shoplistDistanceTv = dataBinding.shoplistDistanceTv;

        arrawType = dataBinding.arrawType;

        arrawSer = dataBinding.arrawSer;

        arrawDis = dataBinding.arrawDis;

        typeLayout = dataBinding.typeLayout;


        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            PermissionUtil.checkPermission(this,Manifest.permission.ACCESS_FINE_LOCATION,getResources().getString(R.string.location_permission));
        }
        dataBinding.titleLayout.settingTitle.setText("消费商家");
        dataBinding.titleLayout.back.setOnClickListener(this);
        dataBinding.shoplistDistance.setOnClickListener(this);
        dataBinding.shoplistSer.setOnClickListener(this);
        dataBinding.shoplistType.setOnClickListener(this);
        dataBinding.mySearch.setSearchViewListener(s -> {
            if (TextUtils.isEmpty(s)) {
                PubUtils.popTipOrWarn(BusinessActivity.this, "您未输入任何内容");
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("word", s);
                bundle.putString("door", s);
                JumpUtils.jumptoNatvie(BusinessActivity.this, "netsearch", 0, bundle);
            }
        });

        door = getIntent().getStringExtra("door");

        arraws = new ArrayList<>();
        arraws.add(arrawType);
        arraws.add(arrawSer);
        arraws.add(arrawDis);


        mDistanceList.add("全部距离");
        mDistanceList.add("500米");
        mDistanceList.add("1000米");
        mDistanceList.add("2000米");
        mDistanceList.add("5000米");

        layout = (LinearLayout) getLayoutInflater().inflate(R.layout.pup_selectlist, null, false);
        popupWindow = new PopupWindow(layout, LinearLayout.LayoutParams.MATCH_PARENT, 600);

        popRv = (RecyclerView) layout.findViewById(R.id.pop_rv);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        popRv.setLayoutManager(manager);
        popRvAdapter = new PopRvAdapter(this, 0);
        popRv.setAdapter(popRvAdapter);

        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        // 设置PopupWindow是否能响应外部点击事件
        popupWindow.setOutsideTouchable(true);
        // 设置PopupWindow是否能响应点击事件
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        backgroundAlpha(1f);

        //添加pop窗口关闭事件
        popupWindow.setOnDismissListener(new poponDismissListener());

        businessAdapter = new BusinessAdapter(this);
        dataBinding.contentList.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.contentList.setAdapter(businessAdapter);

        dataBinding.swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPager = 1;
                mPresenter.getShopList(serviceType, areaType, distanceType, currentPager, 0);
            }
        });
        dataBinding.swipeRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getShopList(serviceType, areaType, distanceType, currentPager, type);
            }
        });
    }


    @Override
    public void granted() {
        initLocation();
        requestLocation();

        shopType = getIntent().getExtras().getInt("type_id",-1);
        //延迟加载
        if(shopType==-1){
            currentPager = 1;
            mPresenter.getShopList(serviceType, areaType, distanceType, currentPager, 0);
        }

    }
    private void requestLocation() {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getCode() == MessageEvent.CODE_LOCTION) {
            EventBus.getDefault().unregister(this);

            currentPager = 1;
            mPresenter.getShopList(serviceType, areaType, distanceType, currentPager, 0);
        }
    }
    @Override
    public void denied() {

    }

    class poponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
            if (lastSelected != -1) {
                arraws.get(lastSelected).setRotation(0);
            }
        }

    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }


    @Override
    protected void updateViews() {
        mPresenter.quryShopRegionApp();
        mPresenter.quryShopTypeApp();
    }

    @Override
    public void getShopingSucc(List<ShopListRes.ShopListInfosBean> listInfosBeans) {
        if (currentPager == 1){
            this.shopListInfos.clear();
        }

        this.shopListInfos.addAll(listInfosBeans);

        if (shopListInfos != null) {
            businessAdapter.setItemData(shopListInfos, door);
        }

        boolean hasMore = listInfosBeans.size() == 15;
        if (hasMore){
            currentPager++;
        }else{
            dataBinding.swipeRefreshLayout.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据
        }
        reFreshLayoutFinish();
    }

    @Override
    public void getShopingFail(String msg) {
        reFreshLayoutFinish();
    }

    @Override
    public void shopSearchSucc(List<ShopListRes.ShopListInfosBean> websiteListInfo) {
        reFreshLayoutFinish();
    }

    @Override
    public void shopSearchFail(String msg) {
        reFreshLayoutFinish();
    }

    private void reFreshLayoutFinish(){
        dataBinding.swipeRefreshLayout.finishRefresh();
        dataBinding.swipeRefreshLayout.finishLoadMore();
    }

    @Override
    public void quryShopRegionAppFail() {
        reFreshLayoutFinish();
    }

    @Override
    public void quryShopRegionAppSucc(QuryShopRegionAppRes serviceTypeRes) {
        shopRegionInfos = serviceTypeRes.getShopRegionInfos();
        if (shopRegionInfos != null) {
            mAreaList.clear();
            mAreaList.add("全部商圈");
            for (int i = 0; i < shopRegionInfos.size(); i++) {
                mAreaList.add(shopRegionInfos.get(i).getName());
            }
        }
    }

    @Override
    public void quryShopTypeAppSucc(QuryShopTypeAppRes serviceTypeRes) {
        shopTypeInfos = serviceTypeRes.getShopTypeInfos();
        if (shopTypeInfos != null) {
            mServiceList.clear();
            mServiceList.add("全部商家");

            boolean shopTypeFalse = true;
            for (int i = 0; i < shopTypeInfos.size(); i++) {
                mServiceList.add(shopTypeInfos.get(i).getType_name());

                if(shopType!=-1){
                    if(shopTypeInfos.get(i).getType_id() == shopType){
                        //传入的id  存在于 后台传来的id中
                        int shop_region_id = shopTypeInfos.get(i).getType_id();
                        serviceType = shop_region_id + "";
                        dataBinding.bussinessSerTv.setTextColor(getResources().getColor(R.color.color_00AAFF));
                        dataBinding.bussinessSerTv.setText(shopTypeInfos.get(i).getType_name());
                        popupWindow.dismiss();
                        currentPager = 1;
                        shopTypeFalse = false;
                        mPresenter.getShopList(serviceType, areaType, distanceType, currentPager, 0);

                    }
                }
            }

            //如果传入的值 不存在 后台的列表里  请求全部
            if(shopTypeFalse){
                currentPager = 1;
                mPresenter.getShopList(serviceType, areaType, distanceType, currentPager, 0);
            }

        }
    }

    @Override
    public void quryShopTypeAppFail() {
        reFreshLayoutFinish();
    }

    private int[] location = new int[2];

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                typeLayout.getLocationOnScreen(location);
                if (ev.getY() < location[1] || ev.getY() > location[1] + typeLayout.getHeight()) {
                    isPopupWindowShow = false;
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.trans_layout) {
            popupWindow.dismiss();
            isPopupWindowShow = false;
        } else if (id == R.id.back) {
            finish();
        } else if (id == R.id.shoplist_distance) {
            if (lastSelected == 2 && isPopupWindowShow) {
                popupWindow.dismiss();
                isPopupWindowShow = false;
            } else {
                isHidePop(2);
                popRvAdapter.setItemViewData(mDistanceList);
                popRvAdapter.notifyDataSetChanged();
                popupWindow.showAsDropDown(v);
                popRvAdapter.popItemOnclick(new PopRvAdapter.PopItemInterface() {
                    @Override
                    public void onClick(View view, int position) {
                        if (position == 0) {
                            dataBinding.bussinessDisTv.setTextColor(getResources().getColor(R.color.color_3d494f));
                        } else {
                            dataBinding.bussinessDisTv.setTextColor(getResources().getColor(R.color.color_00AAFF));
                        }
                        String dis = mDistanceList.get(position);
                        currentPager = 1;
                        L.e(Constant.TAG, "选择的距离-----：" + dis);
                        setDistanceId(mDistanceList.get(position));
                        dataBinding.bussinessDisTv.setText(mDistanceList.get(position));
                        L.e(Constant.TAG, "选择的距离：" + distanceType);
                        mPresenter.getShopList(serviceType, areaType, distanceType, currentPager, 0);
                        popupWindow.dismiss();
                        isPopupWindowShow = false;
                    }
                });
            }
        } else if (id == R.id.shoplist_ser) {
            if (lastSelected == 1 && isPopupWindowShow) {
                popupWindow.dismiss();
                isPopupWindowShow = false;
            } else {
                isHidePop(1);

                popRvAdapter.setItemViewData(mServiceList);
                popRvAdapter.notifyDataSetChanged();
                popupWindow.showAsDropDown(v);
                popRvAdapter.popItemOnclick(new PopRvAdapter.PopItemInterface() {
                    @Override
                    public void onClick(View view, int position) {
                        if (position != 0) {
                            int shop_region_id = shopTypeInfos.get(position - 1).getType_id();
                            serviceType = shop_region_id + "";

                            dataBinding.bussinessSerTv.setTextColor(getResources().getColor(R.color.color_00AAFF));
                        } else {
                            serviceType = "0";
                            dataBinding.bussinessSerTv.setTextColor(getResources().getColor(R.color.color_3d494f));
                        }
                        dataBinding.bussinessSerTv.setText(mServiceList.get(position));
                        popupWindow.dismiss();
                        currentPager = 1;
                        mPresenter.getShopList(serviceType, areaType, distanceType, currentPager, 0);
//                            dataBinding.contentList.startLoadFirst();
                        isPopupWindowShow = false;
                    }
                });
            }
        } else if (id == R.id.shoplist_type) {
            if (lastSelected == 0 && isPopupWindowShow) {
                popupWindow.dismiss();
                isPopupWindowShow = false;
            } else {
                isHidePop(0);

                popRvAdapter.setItemViewData(mAreaList);
                popRvAdapter.notifyDataSetChanged();
                popupWindow.showAsDropDown(v);
                popRvAdapter.popItemOnclick(new PopRvAdapter.PopItemInterface() {
                    @Override
                    public void onClick(View view, int position) {
                        if (position != 0) {
                            int shop_region_id = shopRegionInfos.get(position - 1).getShop_region_id();
                            areaType = shop_region_id + "";
                            dataBinding.shoplistDistanceTv.setTextColor(getResources().getColor(R.color.color_00AAFF));
                        } else {
                            areaType = "0";
                            dataBinding.shoplistDistanceTv.setTextColor(getResources().getColor(R.color.color_3d494f));
                        }
                        dataBinding.shoplistDistanceTv.setText(mAreaList.get(position));
                        currentPager = 1;
                        mPresenter.getShopList(serviceType, areaType, distanceType, currentPager, 0);
                        popupWindow.dismiss();
                        isPopupWindowShow = false;
                    }
                });
            }
        }
    }

    public void setDistanceId(String distanceId) {

        if (distanceId.contains("全部距离")) {
            distanceType = "0";
        } else if (distanceId.equals("500米")) {
            distanceType = "1";
        } else if (distanceId.contains("1000")) {
            distanceType = "2";
        } else if (distanceId.contains("2000")) {
            distanceType = "3";
        } else if (distanceId.contains("5000")) {
            distanceType = "4";
        }
    }

    private void isHidePop(final int position) {
        if (lastSelected == -1) {
            lastSelected = position;
            ViewCompat.animate(arraws.get(position))
                    .rotation(180)
                    .setDuration(100)
                    .start();
            isPopupWindowShow = true;
        } else if (lastSelected == position) {//收起当前箭头
            ViewCompat.animate(arraws.get(position))
                    .rotation(180)
                    .setDuration(100)
                    .start();
            isPopupWindowShow = true;
        } else if (lastSelected != position) {//收起其他箭头
            arraws.get(position).setRotation(180);
            arraws.get(lastSelected).setRotation(0);
            lastSelected = position;
            isPopupWindowShow = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        distanceType = "0";
        areaType = "0";
        serviceType = "0";
    }



    //----------以下动态获取权限---------
    @Override
    protected void onResume() {
        super.onResume();


    }
    private void initLocation() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }
}
